package root.electronclass.electronclass.ext

import android.widget.TextView
import root.electronclass.electronclass.R
import com.google.android.material.tabs.TabLayout

/**
 *
 * @author Lokiy
 * @date 2023/2/4 12:50
 */

fun TabLayout.tabs(tabs: Array<String>, onSelected: (String) -> Unit) {
    tabs.forEach {
        addTab(newTab().setCustomView(R.layout.view_tab_item).setText(it).apply {
            val customView = customView ?: return@apply
            if (customView is TextView) {
                customView.text = it
            }
        })
    }
    doOnTabSelected { onSelected.invoke(it?.text?.toString()?:return@doOnTabSelected) }
}

fun TabLayout.doOnTabSelected(onSelected: (TabLayout.Tab?) -> Unit) {
    val listener = object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            onSelected.invoke(tab)
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }
    }
    getTag(R.id.tab)?.let { removeOnTabSelectedListener(it as TabLayout.OnTabSelectedListener) }
    addOnTabSelectedListener(listener.also { setTag(R.id.tab, it) })
}